package com.example.channel

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import org.junit.Test


/**
 * 协程通道测试
 * 说明：通道是协程安全通信的机制
 *
 * @author zhouronghua
 * @time 2022/1/4 8:39 上午
 */
class ChannelTest {

    /**
     * 测试协程通道容量
     *
     * @author zhouronghua
     * @time 2022/1/4 8:41 上午
     */
    @Test
    fun test_channel_capacity() = runBlocking {
        val channel = Channel<Int>()
        // 生产者发送消息
        val producer = GlobalScope.launch {
            var i = 0
            while (true) {
                channel.send(++ i)
                println("send $i")
                delay(1000)
            }
        }
        // 消费者接收消息
        val consumer = GlobalScope.launch {
            while (true) {
                var elment = channel.receive()
                println("receive $elment")
                delay(1000)
            }
        }
        joinAll(producer, consumer)
    }

}